<?php
  function getKeyMeans($reverse = FALSE) {
    $keyMeans = array(
      "givenName"               => "name_first",
      "sn"                      => "name_last",
      "mozillaNickname"         => "name_nick",
      "mail"                    => "mail_first",
      "mozillaSecondEmail"      => "mail_second",
      "telephoneNumber"         => "phone_work",
      "homePhone"               => "phone_home",
      "mobile"                  => "phone_mobile",
      "homeStreet"              => "street",
      "mozillaHomeLocalityName" => "place",
      "mozillaHomeState"        => "state",
      "mozillaHomePostalCode"   => "post_code",
      "mozillaHomeCountryName"  => "country",
      "mozillaHomeUrl"          => "homepage",
      "description"             => "notes"
    );

    if ($reverse) {
      $temp = array();
      foreach (array_keys($keyMeans) as $key) {
        $temp[$keyMeans[$key]] = $key;
      }
      $keyMeans = $temp;
    }

    return $keyMeans;
  }

  function parseLine($line, $key, $val) {
    $pos = strpos($line, ":");

    $key = substr($line, 0, $pos);

    $line = trim($line);
    $val  = ($line[$pos + 1] == ":")
            ? trim(iconv("UTF-8", "ISO-8859-1", base64_decode(substr($line, $pos + 3))))
            : substr($line, $pos + 2);
  }

  function loadLDIF($filename) {
    $file     = file($filename);
    $filenameInfo = pathinfo($filename);
    $filename = $filenameInfo['basename'];
    $contacts = array();

    $keyMeans = getKeyMeans();

    foreach ($file as $line) {
      parseLine($line, &$key, &$val);

      if ($key == "dn") {
        if ($contact) {
        	$contact['groupName'] = $filename;
        	$contact['id'] = MD5(implode($contact));
        	
          $contacts[] = $contact;
        }
        $contact = getNewContact();
      } else {
        if (array_key_exists($key, $keyMeans)) {
          $contact[$keyMeans[$key]] = $val;
        }
      }
    }
    if ($contact) {
      $contact['groupName'] = $filename;
      $contact['id'] = MD5(implode($contact));
      
      $contacts[] = $contact;
    }

    return $contacts;
  }

  function makeLine($key, $val) {
    return "$key:: " . base64_encode(iconv("ISO-8859-1", "UTF-8", $val)) . "\n";
  }

  function saveLDIF($contacts, $file) {
    $keyMeans = getKeyMeans(TRUE);

    $pointer = fopen($file, "w+");

    foreach ($contacts as $contact) {
      if (($cn = $contact["name_first"] . " " . $contact["name_last"]) != " ") {
        fputs($pointer, makeLine("dn", "cn=$cn"));
        fputs($pointer, makeLine("cn", $cn));
      } else {
        fputs($pointer, makeLine("dn", "mail=" . $contact["mail_first"]));
      }

      foreach (array_keys($contact) as $key) {
        if (($val = $contact[$key]) != "" && array_key_exists($key, $keyMeans)) {
          fputs($pointer, makeLine($keyMeans[$key], $contact[$key]));
        }
      }

      fputs($pointer, "\n");
    }

    fclose($pointer);
  }
?>